"""
投诉类型分析API路由
提供投诉类型分析相关的API接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from typing import Optional, Dict, Any, List
from pydantic import BaseModel, Field
from datetime import datetime
from sqlalchemy.orm import Session

from core.database import get_db
from core.auth import get_current_active_user
from models.user import User
from services.analysis.complaint_analyzer import ComplaintAnalyzer, ComplaintAnalysisFilters
from services.analysis.base_analyzer import get_analysis_service

# 创建路由器
complaint_analysis_router = APIRouter()

# 请求模型
class ComplaintAnalysisRequest(BaseModel):
    """投诉类型分析请求模型"""
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")
    type_level: Optional[str] = Field(None, description="类型级别: level1, level2, level3")
    complaint_type: Optional[str] = Field(None, description="特定投诉类型")
    min_confidence: Optional[float] = Field(None, ge=0.0, le=1.0, description="最小置信度")
    limit: Optional[int] = Field(1000, ge=1, le=10000, description="返回记录限制")
    offset: Optional[int] = Field(0, ge=0, description="偏移量")

class ComplaintTypeTrendsRequest(BaseModel):
    """投诉类型趋势请求模型"""
    complaint_type: str = Field(..., description="投诉类型")
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")

class ComplaintTypeComparisonRequest(BaseModel):
    """投诉类型对比请求模型"""
    type_list: List[str] = Field(..., description="要对比的类型列表")
    task_id: Optional[int] = Field(None, description="分析任务ID")
    start_date: Optional[datetime] = Field(None, description="开始时间")
    end_date: Optional[datetime] = Field(None, description="结束时间")


@complaint_analysis_router.post("/analyze")
async def analyze_complaint_types(
    request: ComplaintAnalysisRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """
    执行投诉类型分析

    返回完整的投诉类型分析结果，包括：
    - 基础统计信息
    - 类型分布数据
    - 层级分析数据
    - 置信度分析
    - 时间序列数据
    - 热门类型
    """
    try:
        # 创建过滤器
        filters = ComplaintAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date
        filters.type_level = request.type_level
        filters.complaint_type = request.complaint_type
        filters.min_confidence = request.min_confidence
        filters.limit = request.limit
        filters.offset = request.offset

        # 执行分析
        analyzer = ComplaintAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        return {
            "code": 200,
            "message": "投诉类型分析完成",
            "data": result.data,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"投诉类型分析失败: {str(e)}")


@complaint_analysis_router.get("/distribution")
async def get_complaint_type_distribution(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    type_level: Optional[str] = Query("level2", description="类型级别: level1, level2, level3"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    limit: Optional[int] = Query(15, ge=1, le=50, description="返回类型数量限制"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取投诉类型分布统计数据"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.type_level = type_level
        filters.limit = limit

        analyzer = ComplaintAnalyzer(db)
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_type_distribution(query, filters)

        return {
            "code": 200,
            "message": "获取投诉类型分布成功",
            "data": distribution,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取投诉类型分布失败: {str(e)}")


@complaint_analysis_router.get("/hierarchy")
async def get_complaint_type_hierarchy(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取投诉类型层级结构"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date

        analyzer = ComplaintAnalyzer(db)
        query = analyzer.build_base_query(filters)
        hierarchy = analyzer.get_hierarchy_analysis(query, filters)

        return {
            "code": 200,
            "message": "获取类型层级结构成功",
            "data": hierarchy,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取类型层级结构失败: {str(e)}")


@complaint_analysis_router.get("/confidence-analysis")
async def get_complaint_confidence_analysis(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    complaint_type: Optional[str] = Query(None, description="特定投诉类型"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取投诉类型置信度分析"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.complaint_type = complaint_type

        analyzer = ComplaintAnalyzer(db)
        query = analyzer.build_base_query(filters)
        confidence_analysis = analyzer.get_confidence_analysis(query, filters)

        return {
            "code": 200,
            "message": "获取置信度分析成功",
            "data": confidence_analysis,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取置信度分析失败: {str(e)}")


@complaint_analysis_router.get("/popular-types")
async def get_popular_complaint_types(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    limit: Optional[int] = Query(10, ge=1, le=20, description="返回类型数量限制"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取热门投诉类型"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date

        analyzer = ComplaintAnalyzer(db)
        query = analyzer.build_base_query(filters)
        popular_types = analyzer.get_popular_types(query, filters, limit)

        return {
            "code": 200,
            "message": "获取热门类型成功",
            "data": popular_types,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取热门类型失败: {str(e)}")


@complaint_analysis_router.post("/type-trends")
async def get_complaint_type_trends(
    request: ComplaintTypeTrendsRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取特定投诉类型的时间趋势"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date

        analyzer = ComplaintAnalyzer(db)
        trends = analyzer.get_type_trends(request.complaint_type, filters)

        return {
            "code": 200,
            "message": "获取类型趋势成功",
            "data": trends,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取类型趋势失败: {str(e)}")


@complaint_analysis_router.post("/type-comparison")
async def compare_complaint_types(
    request: ComplaintTypeComparisonRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """对比多个投诉类型"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = request.task_id
        filters.start_date = request.start_date
        filters.end_date = request.end_date

        analyzer = ComplaintAnalyzer(db)
        comparison = analyzer.get_type_comparison(request.type_list, filters)

        return {
            "code": 200,
            "message": "类型对比分析完成",
            "data": comparison,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"类型对比分析失败: {str(e)}")


@complaint_analysis_router.get("/time-series")
async def get_complaint_time_series(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    complaint_type: Optional[str] = Query(None, description="特定投诉类型"),
    granularity: Optional[str] = Query("day", description="时间粒度: day, week, month"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取投诉类型时间序列数据"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.complaint_type = complaint_type

        analyzer = ComplaintAnalyzer(db)
        time_series = analyzer.get_time_series_data(filters, granularity)

        return {
            "code": 200,
            "message": "获取时间序列成功",
            "data": time_series,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取时间序列失败: {str(e)}")


@complaint_analysis_router.get("/summary")
async def get_complaint_summary(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取投诉类型分析摘要"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date

        analyzer = ComplaintAnalyzer(db)
        basic_stats = analyzer.get_basic_statistics(filters)

        # 获取简要的类型分布
        query = analyzer.build_base_query(filters)
        distribution = analyzer.get_type_distribution(query, filters)

        # 获取置信度分析
        confidence_analysis = analyzer.get_confidence_analysis(query, filters)

        summary = {
            "basic_statistics": basic_stats,
            "top_types": distribution.get("types", [])[:5],
            "top_counts": distribution.get("counts", [])[:5],
            "total_types": distribution.get("total_types", 0),
            "average_confidence": confidence_analysis.get("average_confidence", 0),
            "most_common_type": distribution.get("most_common_type", "无")
        }

        return {
            "code": 200,
            "message": "获取投诉类型摘要成功",
            "data": summary,
            "timestamp": datetime.now().isoformat()
        }

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取投诉类型摘要失败: {str(e)}")


@complaint_analysis_router.get("/export")
async def export_complaint_data(
    task_id: Optional[int] = Query(None, description="分析任务ID"),
    start_date: Optional[datetime] = Query(None, description="开始时间"),
    end_date: Optional[datetime] = Query(None, description="结束时间"),
    type_level: Optional[str] = Query("level2", description="类型级别"),
    complaint_type: Optional[str] = Query(None, description="特定投诉类型"),
    format: str = Query("json", description="导出格式: json, csv"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """导出投诉类型分析数据"""
    try:
        filters = ComplaintAnalysisFilters()
        filters.task_id = task_id
        filters.start_date = start_date
        filters.end_date = end_date
        filters.type_level = type_level
        filters.complaint_type = complaint_type

        analyzer = ComplaintAnalyzer(db)
        result = analyzer.analyze_data(filters)

        if not result.success:
            raise HTTPException(status_code=400, detail=result.message)

        if format == "json":
            return {
                "code": 200,
                "message": "数据导出成功",
                "data": result.data,
                "format": "json",
                "timestamp": datetime.now().isoformat()
            }
        elif format == "csv":
            # 这里可以实现CSV导出逻辑
            raise HTTPException(status_code=400, detail="CSV导出功能待实现")
        else:
            raise HTTPException(status_code=400, detail="不支持的导出格式")

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导出数据失败: {str(e)}")